package com.jiukuaidao.library.common;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Environment;
import android.os.Looper;

import com.jiukuaidao.library.util.PackageUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Author : PaiTaSuo
 * Date : 2016/5/13
 * Description : App异常崩溃
 */
public class AppException extends Exception implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Context mContext;
    private Class<?> mClazz;
    private boolean mIsSaveLog;

    private AppException(Context context, Class<?> clazz, boolean isSaveLog) {
        mContext = context;
        mClazz = clazz;
        mIsSaveLog = isSaveLog;

        this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    /**
     * 获取APP异常崩溃处理对象
     *
     * @return
     */

    public static class Builder {
        private Context mContext;
        private boolean mIsSaveLog;
        private Class mActivity;

        /**
         * 异常结束后跳转的Activity.
         */
        public Builder activity(Class<?> clazz) {
            mActivity = clazz;
            return this;
        }

        public Builder context(Context context) {
            mContext = context;
            return this;
        }

        public Builder isSaveLog(boolean isSaveLog) {
            mIsSaveLog = isSaveLog;
            return this;
        }


        public AppException build() {
            return new AppException(mContext, mActivity, mIsSaveLog);
        }


    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        ex.printStackTrace();
        if (!handleException(ex) && mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    /**
     * 自定义异常处理:收集错误信息&发送错误报告
     *
     * @param ex
     * @return true:处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        final Context context = AppManager.getAppManager().currentActivity();

        if (context == null) {
            return false;
        }

        final String crashReport = getCrashReport(ex);
        new Thread() {
            public void run() {
                Looper.prepare();
                sendAppCrashReport(crashReport);
                Looper.loop();
            }

        }.start();
        return true;
    }

    /**
     * 发送App异常崩溃报告
     *
     * @param crashReport
     */
    public void sendAppCrashReport(final String crashReport) {
        if (mIsSaveLog) {
            saveErrorLog(crashReport);
        }

        if (mClazz != null && mContext != null) {
            Intent intent = new Intent(mContext, mClazz);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    /**
     * 获取APP崩溃异常报告
     *
     * @param ex
     * @return
     */
    private String getCrashReport(Throwable ex) {
        PackageInfo pinfo = PackageUtils.getPackageInfo();
        StringBuffer exceptionStr = new StringBuffer();
        exceptionStr.append("Version: " + pinfo.versionName + "(" + pinfo.versionCode + ")\n");
        exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE + "(" + android.os.Build.MODEL + ")\n");
        exceptionStr.append("Exception: " + ex.getMessage() + "\n");
        StackTraceElement[] elements = ex.getStackTrace();
        for (int i = 0; i < elements.length; i++) {
            exceptionStr.append(elements[i].toString() + "\n");
        }
        return exceptionStr.toString();
    }

    /**
     * 保存异常日志
     *
     * @param excp
     * @return
     */
    @SuppressWarnings("deprecation")
    public static void saveErrorLog(String excp) {
        String errorlog = "errorlog.txt";
        String savePath = "";
        String logFilePath = "";
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            // 判断是否挂载了SD卡
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                savePath = Environment.getExternalStorageDirectory() + "/JKDZhuLin/Log/";
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                logFilePath = savePath + errorlog;
            }
            if (logFilePath == "") {
                return;
            }
            File logFile = new File(logFilePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            fw = new FileWriter(logFile, true);
            pw = new PrintWriter(fw);
            pw.println("--------------------" + (new Date().toLocaleString()) + "---------------------");
            pw.print(excp);
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }

    }
}
